<template>
  <el-form ref='form' :inline="true" :model='modelValue' class="demo-form-inline">
    <template v-for='(item,index) in filterArray'>
      <el-form-item :label="item.label" v-if='item.show??=true' :key='index'>
        <el-input :style="{width: item.width}" v-model="modelValue[item.prop]" v-bind='item.attrs' v-if='item.itemType ==="input"'/>
        <el-select :style="{width: item.width}" v-model="modelValue[item.prop]" v-bind='item.attrs' v-else-if='item.itemType ==="select"'>
          <el-option v-bind='items' v-for='(items,index) in item.options' :key='index'/>
        </el-select>
        <el-date-picker :style="{width: item.width}" :value-format='dataFormat(item)' v-model='modelValue[item.prop]' v-bind='item.attrs' v-else-if='item.itemType ==="date"' />
        <slot :name="item.prop" :scope="item" v-else-if="item.itemType==='slot'">【自定义插槽】</slot>
      </el-form-item>
    </template>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" v-if="showSearchBtn">查询</el-button>
      <el-button type="primary" @click="onReset" v-if="showResetBtn">重置</el-button>
      <slot name="menu-right"></slot>
    </el-form-item>

  </el-form>
</template>

<script>
export default {
  name: 'Filter'
}
</script>

<script setup>
import { inject, watch, computed } from 'vue'
import { useAttrs } from 'vue'
let props = defineProps({
  modelValue: {
    type: Object,
    default: () =>{}
  },
  filterArray: {
    type: Array,
    default: () =>[]
  },
  init: {
    type: Boolean,
    default: false
  },
  showSearchBtn: {
    type: Boolean,
    default: true
  }
})

const attrs = useAttrs()
console.log(attrs)

// 订阅initParams方法
const initParams = inject('initParams')

// 格式化日期选择器返回值
const dataFormat = (e)=>{
  let type = e?.attrs?.type
  if(type){
    if(e.attrs.valueFormat){
      return e.attrs.valueFormat
    }else if(type.includes('time')){
      return 'YYYY-MM-DD HH:mm:ss'
    }else {
      return 'YYYY-MM-DD'
    }
  }else {
    return 'YYYY-MM-DD'
  }
}
// 处理日期范围选择器赋值
let formInlineComp = computed(()=>{
  let form = JSON.parse(JSON.stringify(props.modelValue))
  Object.keys(form).map(item =>{
    if(item.includes(',')){
      let arr = item.split(',')
      form[arr[0]] = form[item] ? form[item][0] : ''
      form[arr[1]] = form[item] ? form[item][1] : ''
      delete(form[item])
    }
  })
  return form
})
// 初始化默认值并调用接口
watch(() => props.filterArray, (n)=>{
  if(props.init){
    initParams(formInlineComp)
  }
},{
  immediate:true,
  deep: true
})


const onSubmit = () => {
  initParams(formInlineComp)
}

const onReset = () => {

}

</script>

<style scoped>

</style>
